package com.fs.controller;

import com.fs.annotation.SysLog;
import com.fs.service.CaptService;
import com.fs.service.EmailService;
import com.fs.service.UserService;
import com.fs.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@Api(tags = "登陆管理")
@RestController
public class UserLoginController {

    @Autowired
    private CaptService captService;

    @Autowired
    private UserService userService;
    @Autowired
    private EmailService emailService;

    @PostMapping("/reg")
    public ResultVO reg(@RequestBody RegFormVO formVO){
        return userService.reg(formVO);
    }

    @PostMapping("/sendRegisterEmail")
    public ResultVO sendRegisterEmail(@RequestBody RegisterSendEmailVO email){
        return emailService.sendRegisterEmail(email.getEmail(),1);
    }

    @PostMapping("/sendForgetEmail")
    public ResultVO sendForgetEmail(@RequestBody RegisterSendEmailVO email){
        return emailService.sendForgetEmail(email.getEmail(),2);
    }

    @PostMapping("/forget")
    public ResultVO forget(@RequestBody ForgetVO vo){
        return userService.forget(vo);
    }


    @SysLog("用户登陆")
    @PostMapping("/login")
    public ResultVO login(@RequestBody LoginVO vo){
        return userService.login(vo);
    }

    @SysLog("退出")
    @ApiOperation(value = "退出", notes = "参数:token")
    @PostMapping("/logout")
    public ResultVO logout(@RequestHeader("token")String token) {
        ResultVO result = new ResultVO();
//        shiroService.logout(token);
        result.setStatus(200).setMsg("您已安全退出系统");
        return result;
    }

    /**
     * 验证码
     */
    @ApiOperation(value = "获取验证码")
    @GetMapping("/captcha.jpg")
    public ResultVO captchaJpg()throws IOException {
        String uuid= UUID.randomUUID().toString();
        BufferedImage image = captService.getCaptcha(uuid);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        ImageIO.write(image, "jpg", baos);//写入流中
        BASE64Encoder encoder = new BASE64Encoder();
        byte[] bytes = baos.toByteArray();//转换成字节
        String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n

        HashMap<String, String> map = new HashMap<>();
        map.put("uuid",uuid);
        map.put("img","data:image/jpg;base64,"+png_base64);

        return ResultVO.success(map);
    }
}
